//
//  UITextView+CAPlaceholder.m
//  Conva
//
//  Created by Lin on 2018/1/7.
//  Copyright © 2018年 com.conva. All rights reserved.
//

#import "UITextView+CAPlaceholder.h"
#import <objc/runtime.h>
#import <Masonry/Masonry.h>

@implementation UITextView (CAPlaceholder)

- (NSString*)ca_placeholder
{
    return objc_getAssociatedObject(self, @selector(ca_placeholder));
}
- (void)setCa_placeholder:(NSString*)ca_placeholder
{
    objc_setAssociatedObject(self, @selector(ca_placeholder), ca_placeholder, OBJC_ASSOCIATION_ASSIGN);
    self.ca_labelPlaceholder.text = ca_placeholder;
}

- (UILabel*)ca_labelPlaceholder
{
    if (!objc_getAssociatedObject(self, @selector(ca_labelPlaceholder))) {
        UILabel* label = [UILabel new];
        label.text = self.ca_placeholder;
        label.textColor = [UIColor colorWithRed:200 / 255.f green:200 / 255.f blue:200 / 255.f alpha:1];
        label.numberOfLines = 0;
        label.font = self.font;
        label.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self).offset(self.textContainerInset.top+5);
            //TODO 这里不知道为什么left有一定的偏移,暂时写死,没对字体大小变化进行测试
            make.left.equalTo(self).offset(self.textContainerInset.left+20);
            make.right.equalTo(self).offset(self.textContainerInset.right);
            make.bottom.equalTo(self).offset(self.textContainerInset.bottom);
        }];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:nil];
        objc_setAssociatedObject(self, _cmd, label, OBJC_ASSOCIATION_ASSIGN);
    }
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setCa_labelPlaceholder:(UILabel*)ca_labelPlaceholder
{
    objc_setAssociatedObject(self, @selector(ca_labelPlaceholder), ca_labelPlaceholder, OBJC_ASSOCIATION_ASSIGN);
}

- (UIColor*)ca_placeholderColor
{
    return self.ca_labelPlaceholder.textColor;
}
- (void)setCa_placeholderColor:(UIColor*)ca_placeholderColor
{
    self.ca_labelPlaceholder.textColor = ca_placeholderColor;
}

- (UIFont*)ca_placeholderFont
{
    return self.ca_labelPlaceholder.font;
}
- (void)setCa_placeholderFont:(UIFont*)ca_placeholderFont
{
    self.ca_labelPlaceholder.font = ca_placeholderFont;
}

- (void)textDidChange:(NSNotification *)notification
{
    if(notification.object == self){
        if (self.text.length > 0) {
            self.ca_labelPlaceholder.hidden = YES;
        }
        else {
            self.ca_labelPlaceholder.hidden = NO;
        }
    }
}

@end
